#include "LogParser.h"

LogParser::LogParser()
{
	m_Time = 0.0f;
	m_NameTeamLeft.clear();
	m_NameTeamRight.clear();
	m_ScoreLeft = 0;
	m_ScoreRight = 0;
}
LogParser::~LogParser()
{

}
bool LogParser::MonitorLogParse( std::string logPath, std::vector<WorldModelNode*> &wm )
{
	FILE *fp;

	if( (fp = fopen(logPath.c_str(),"r")) == NULL )
	{
		std::cout<<"[Error]: " << "Can't open log file " << "\n";
		return false;
	}

	char buff[200000];

	//std::ofstream fop;
	//fop.open( "parsed_log.log" );

	int line_idx = 1;
	while( fgets( buff,200000,fp ) )
	{
		Predicate *root_p = new Predicate();
		if( ! LineParse( &root_p, std::string(buff) ) )
		{
			return false;
		}
		
		WorldModelNode *wmNode = new WorldModelNode;
		wmNode->Update( root_p );
		wmNode->Context() = std::string(buff);
		wm.push_back( wmNode );

		SetInfo( wmNode );

 		std::string output;
 		root_p->PrintAll( output );
		//fop << "line: " << line_idx++ << "\n";
 		//fop << output;

//		delete root_p;
//		root_p = NULL;
		//Clear( root_p );
	}

	fclose(fp);
	//fop.close();

	return true;
}
void LogParser::SetInfo( WorldModelNode *wmNode )
{
	if( wmNode->Time() > 0.0f )
	{
		m_Time = wmNode->Time();
	}
	if( !wmNode->NameTeamLeft().empty() )
	{
		m_NameTeamLeft = wmNode->NameTeamLeft();
	}
	if( !wmNode->NameTeamRight().empty() )
	{
		m_NameTeamRight = wmNode->NameTeamRight();
	}
	if( (int)wmNode->ScoreTeamLeft() > m_ScoreLeft )
	{
		m_ScoreLeft = (int)wmNode->ScoreTeamLeft();
	}
	if( (int)wmNode->ScoreTeamLeft() > m_ScoreRight )
	{
		m_ScoreRight = (int)wmNode->ScoreTeamLeft();
	}

	wmNode->SetTime( m_Time );
	wmNode->SetNameTeamLeft( m_NameTeamLeft );
	wmNode->SetNameTeamRight( m_NameTeamRight );
	wmNode->SetScoreLeft( m_ScoreLeft );
	wmNode->SetScoreLeft( m_ScoreRight );
}
bool LogParser::LineParse( Predicate** pred, const std::string &msg )
{
	int head = (int)msg.find("(");

	if( head == -1 )
	{
		return true;
	}

	if( !Parser::Parse( msg.substr(head), pred ) )
	{
		return false;
	}

	return true;
}
void LogParser::Clear( Predicate* root )
{
	std::cout<< "begin\n";
	if( root == NULL )
	{
		return;
	}

	for( std::multimap<std::string, Predicate*>::iterator mit = root->child.begin(); 
		mit != root->child.end(); mit ++ )
	{
		Predicate* p = (*mit).second;
		std::cout<< p->name << "\n";
		std::cout<< "Clear\n";
		Clear(p);
	}

	delete root;
	//root = NULL;
	std::cout<< "begin2\n";
}